package class02;

import utils.ArrayUtil;

public class Code01_前缀和 {

    /**
     * 根据现有数组构造前缀和数组  一路累加的结果   前缀和
     */
    public static int[] getPreSumArr(int arr[]) {
        int[] preSumArr = new int[arr.length];
        preSumArr[0] = arr[0];
        for (int i = 1; i < preSumArr.length; i++) {
            preSumArr[i] = preSumArr[i - 1] + arr[i];
        }
        return preSumArr;
    }

    /**
     * @Description: 获取区间的数字之和      3-7   =   0-7  -   0-2
     */
    public static int getPreSum(int arr[], int L, int R) {
        int[] preSumArr = getPreSumArr(arr);
        ArrayUtil.printArray(preSumArr);
        return L == 0 ? preSumArr[R] : preSumArr[R] - preSumArr[L-1];
    }

    public static void main(String[] args) {
        //生成定长的正数数组
        int[] arr = ArrayUtil.generateRandomArray(20, 10, false, true);
        ArrayUtil.printArray(arr);
        System.out.println(getPreSum(arr, 3, 7));
    }
}
